<template>
  <div class="location" :class="isMyTableClass && !isOA ? 'myTable' : isOA ? 'auto-height-table' : ''">
    <el-table
      ref="tableRef"
      v-bind="table.props"
      border
      class="table"
      id="myTable"
      :style="{
        height:
          plantSelected.length && isLargeScreen ? 'calc(100% - ' + largeScreenHeight + 'px)' : pagination ? 'calc(100% - 50px)' : '100%',
      }"
      :lazy="true"
      :load="true"
      :data="table.listData"
      @select="select"
      @select-all="selectAll"
    >
      <el-table-column v-if="isIndexOrSelection('selection')" :selectable="selectable" align="center" type="selection" width="40" />
      <el-table-column
        v-if="isIndexOrSelection('index')"
        align="center"
        :index="getIndex"
        label="序号"
        type="index"
        :width="50 + 5 * getIndex(1).length"
      />
      <template v-for="item in table.ExistingFieldsList">
        <el-table-column
          v-if="!item.type"
          :label="item.label"
          :prop="item.prop"
          v-bind="item.props"
          :current-row-key="item.id"
          :class-name="item.class_name ? item.class_name : ''"
          :key="item.id"
        >
          <template #default="{ row }">
            <slot :name="item?.slot?.name" v-bind="row">
              <span :style="{ color: item?.FnColor ? item.FnColor(row) : '' }">
                {{ item?.Fn ? item.Fn(row) : row[item.prop] }}
              </span>
            </slot>
          </template>
        </el-table-column>
        <!-- 列表名称 -->
        <el-table-column
          v-if="item.type === 'name'"
          :label="item.label"
          :prop="item.prop"
          v-bind="item.props"
          :current-row-key="item.id"
          :class-name="item.class_name ? item.class_name : ''"
          :key="item.id"
        >
          <template #default="{ row }">
            <slot :name="item?.slot?.name" v-bind="row">
              <el-button link size="small" type="primary" @click="handleInfoClick(row, '详情')">
                <span style="font-size: 14px">{{ row[item.prop] }}</span>
              </el-button>
            </slot>
          </template>
        </el-table-column>
        <!-- 列表日期 -->
        <el-table-column
          v-if="item.type === 'date'"
          :label="item.label"
          :prop="item.prop"
          v-bind="item.props"
          :current-row-key="item.id"
          :class-name="item.class_name ? item.class_name : ''"
          :key="item.id"
        >
          <template v-slot:default="{ row }">
            <slot :name="item?.slot?.name" v-bind="row">
              <span :style="{ color: row.color }">
                {{ row[item.prop] }}
              </span>
            </slot>
          </template>
        </el-table-column>
        <!-- 列表图片 -->
        <el-table-column
          v-if="item.type === 'img'"
          :label="item.label"
          :prop="item.prop"
          v-bind="item.props"
          :current-row-key="item.id"
          :class-name="item.class_name ? item.class_name : ''"
          :key="item.id"
        >
          <template #default="{ row }">
            <slot :name="item?.slot?.name" v-bind="row">
              <el-image
                v-if="row[item.prop]"
                fit="cover"
                :initial-index="0"
                :max-scale="7"
                :min-scale="0.2"
                :preview-src-list="[row[item.prop]]"
                :preview-teleported="true"
                :src="row[item.prop]"
                style="width: 60px; height: 80px"
                :z-index="3600"
                :zoom-rate="1.2"
              />
            </slot>
          </template>
        </el-table-column>
        <!-- 备注 -->
        <el-table-column
          v-if="item.type === 'remark'"
          :label="item.label"
          :prop="item.prop"
          v-bind="item.props"
          :current-row-key="item.id"
          :class-name="item.class_name ? item.class_name : ''"
          :key="item.id"
        >
          <template #default="{ row }">
            <slot :name="item?.slot?.name" v-bind="row">
              <MyTooltip :conten="row[item.prop]" v-if="row[item.prop]">
                <template #default>
                  <p class="remark">{{ row[item.prop] }}</p>
                </template>
              </MyTooltip>
            </slot>
          </template>
        </el-table-column>
        <!-- 列表状态 -->
        <el-table-column
          v-if="item.type === 'status'"
          :label="item.label"
          :prop="item.prop"
          v-bind="item.props"
          :current-row-key="item.id"
          :class-name="item.class_name ? item.class_name : ''"
          :key="item.id"
        >
          <template #default="{ row }">
            <slot :name="item?.slot?.name" v-bind="row">
              <dict-tag :text="item.dict.text" :dict="row.dict"></dict-tag>
            </slot>
          </template>
        </el-table-column>
      </template>
      <!-- 操作 -->
      <el-table-column
        v-if="table.operateData.show"
        v-bind="table.operateData.props"
        align="center"
        :fixed="table.operateData.fixed"
        :width="table.operateData.width"
      >
        <template #header>
          <slot :name="table?.operateData?.slot?.name">
            <span>{{ table.operateData.label }}</span>
            <vab-icon class="c_main pointer ml4" icon="equalizer-line" @click="handleTableHeader" />
          </slot>
        </template>
        <template #default="{ row }">
          <slot :name="table.operateData?.defaultslot" v-bind="row" :rows="row">
            <el-dropdown szie="mini">
              <span class="el-dropdown-link">操作</span>
              <template #dropdown>
                <el-dropdown-menu class="common-list-dropdown">
                  <el-dropdown-item command="account" @click="handleInfoClick(row, '编辑')">
                    <el-icon><edit /></el-icon>
                    编辑
                  </el-dropdown-item>
                  <el-dropdown-item command="updatePwd" @click="handleClick(row)">
                    <el-icon><delete-filled /></el-icon>
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </slot>
        </template>
      </el-table-column>
      <template #empty>
        <slot name="empty"></slot>
      </template>
    </el-table>
    <!-- 大屏 -->
    <div class="largeScreen" :style="{ height: largeScreenHeight - 50 + 'px' }" v-if="plantSelected.length && isLargeScreen && isLarge">
      <div class="largeScreenTitle">
        <div>
          已选
          <span class="c4e88f3">{{ plantSelected.length }}条</span>
        </div>
        <div class="footerBut">
          <slot name="popoverFooter"></slot>
          <el-button type="danger" @click="handleClearAll">全部清空</el-button>
          <el-button link @click="setCollapse">
            <template v-if="collapse">
              展开
              <el-icon><ArrowUpBold /></el-icon>
            </template>
            <template v-else>
              收起
              <el-icon><ArrowDownBold /></el-icon>
            </template>
          </el-button>
        </div>
      </div>
      <div class="largeContent">
        <div class="popoverContenItem w200" v-for="(item, index) in plantSelected" :key="index">
          <span>{{ item[popoverContenKey] }}</span>
          <el-button color="#aeaeae" :icon="Close" link @click="deletePlantSelected(item, index)" />
        </div>
      </div>
    </div>
    <el-pagination
      v-if="pagination"
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="pageSizes"
      small
      :total="table.total"
      @current-change="currentChange"
      @size-change="sizeChange"
    />
    <!-- 动态表头 -->
    <custom-header ref="CustomHeaderRef" @data-submit="isHeaderSubmit" />
    <!-- 小屏查看选中数据 -->
    <div class="tableSelect" v-if="plantSelected.length && !isLargeScreen && isLarge">
      <el-popover placement="top-start" width="auto" trigger="hover">
        <template #reference>已选{{ plantSelected.length }}</template>
        <template #default>
          <div class="popoverTitle">
            已选
            <span class="c4e88f3">{{ plantSelected.length }}条</span>
          </div>
          <div class="popoverConten">
            <div class="popoverContenItem" v-for="(item, index) in plantSelected" :key="index">
              <span>{{ item[popoverContenKey] }}</span>
              <el-button color="#aeaeae" :icon="Close" link @click="deletePlantSelected(item, index)" />
            </div>
          </div>
          <div class="footerBut">
            <slot name="popoverFooter"></slot>
            <el-button @click="handleClearAll">全部清空</el-button>
          </div>
        </template>
      </el-popover>
    </div>
  </div>
</template>

<script lang="ts" setup>
// import { ArrowDownBold, Close, DeleteFilled, Edit } from '@element-plus/icons-vue'
import { computed, nextTick, onMounted, onUnmounted, onUpdated, ref, watchEffect } from 'vue'
import { useRoute } from 'vue-router'
import indexedDB from './indexedDB'
// import DictTag from '/@/components/DictTag/index.vue'
import CustomHeader from '@/components/myCustomHeader/index.vue'
// import MyTooltip from '/@/components/MyTooltip/index.vue'
// import { formatDate } from '/@/utils'
// import { deepClone } from '/@/utils/index'
const tableRef = ref<any>(null)
const route = useRoute()
const isOA = ref(route.path.includes('fixedOA'))
const CustomHeaderRef = ref<any>(null)
const emit = defineEmits([
  'update:modelValue',
  'update:pageNo',
  'update:pageSize',
  'handleInfoClick',
  'paginationChange',
  'getSelectionData',
  'handleClick',
])
const plantSelected = ref<any[]>([]) //回显数据
const isLargeScreen = ref<boolean>(false) // 当前显示是否大屏
const largeScreenHeight = ref<number>(200) //大屏高度
const collapse = ref<boolean>(true)
const props = defineProps({
  pageSizes: {
    //默认分页
    type: Array,
    default: () => [20, 50, 100],
  },
  pagination: {
    //是否需要分页组件
    type: Boolean,
    default: true,
  },
  popoverContenKey: { type: String, default: 'name' },
  modelValue: { type: Object, default: () => {} }, //表格数据
  pageNo: { type: Number, default: 1 }, //分页页码
  pageSize: { type: Number, default: 10 }, //分页条
  isMyTableClass: { type: Boolean, default: true }, // 是否需要默认样式
  isLarge: { type: Boolean, default: true },
  selectable: { type: Function, default: () => true },
})
// plantSelected数据发生改变就返回出去
watchEffect(() => {
  emit('getSelectionData', plantSelected.value) //返回数据
})
// 分页
const pageSize = computed({
  get: () => props.pageSize,
  set: (val) => emit('update:pageSize', val),
})
const pageNo = computed({
  get: () => props.pageNo,
  set: (val) => emit('update:pageNo', val),
})
const echoData = (data: any) => {
  //默认回显数据
  plantSelected.value = data.selection.defineData
  nextTick(() => {
    if (plantSelected.value && plantSelected.value.length) {
      data.listData.forEach((item: any) => {
        const result = plantSelected.value.find(
          // 保证key一致
          (row) => row[data.selection.rowKey] == item[data.selection.rowKey]
        )
        if (result) {
          tableRef.value.toggleRowSelection(item, true)
        }
      })
    }
  })
}
const operateObj = {
  show: true, //是否需要操作列
  isHeader: true, //是否开始动态表格
  fixed: 'right',
  label: '操作',
  width: '90',
} as any

//初始化表格
const table = computed({
  get: () => {
    const obj = props.modelValue
    // 默认操作
    obj.operateData = !obj.operateData ? {} : obj.operateData
    const keyList = Object.keys(obj.operateData)
    for (const key in operateObj) {
      if (!keyList.includes(key)) {
        obj.operateData[key] = operateObj[key]
      }
    }
    obj.list.forEach((item: any, index: number) => {
      item.id = index + 1 // 方便记录表头字段是否需要
      item.isOprt = false
      if (item.type === 'status') {
        // 处理状态
        for (const row of obj.listData) {
          row.dict =
            'type' in item.dict && item.dict.type.includes(row[item.prop])
              ? {
                  value:
                    item.dict.const[row[item.prop]].value +
                    (item.dict.colorDate(row) ? '' : `(${item.dict.const[row[item.prop]].overdueText})`),
                  color: item.dict.colorDate(row) ? item.dict.const[row[item.prop]].color : item.dict.const[row[item.prop]].overdueColor,
                }
              : item.dict.const[row[item.prop]]
          row.popover = row[item.prop] * 1 > 1 && item.dict.popover && row[item.dict.popoverID]
        }
      }

      if (item.type === 'date') {
        for (const row of obj.listData) {
          row[item.prop] = row[item.prop] ? formatDate(new Date(row[item.prop]), 'YYYY-MM-dd hh:mm') : ''
          row.color = item?.colorDate ? (item.colorDate(row) ? 'var(--el-table-text-color)' : '#f89898') : 'var(--el-table-text-color)'
        }
      }
    })
    if (obj?.total) {
      obj.total = Number(obj.total)
    }
    // 回显默认数据
    if (obj?.selection?.isEcho && obj?.selection?.defineData?.length) {
      echoData(obj)
    }
    return obj
  },
  set: (val) => {
    emit('update:modelValue', val)
  },
}) as any
onUpdated(() => {
  echo()
})
// 获取表头
const getHeader = () => {
  if (table.value.operateData?.isHeader) {
    const idsPromise = indexedDB.getData(route.path).then((res) => {
      if (res?.data) {
        return new Set(res.data.map((item: any) => item.id))
      }
      return null
    })
    Promise.all([idsPromise]).then(([ids]) => {
      if (!ids) {
        table.value.ExistingFieldsList = table.value.list
      } else {
        table.value.ExistingFieldsList = table.value.list.filter((item: any) => ids?.has(item.id))
      }
    })
  } else {
    table.value.ExistingFieldsList = table.value.list
  }
}

const clearSelection = () => {
  // 清空选中
  plantSelected.value.forEach((item) => {
    tableRef.value.toggleRowSelection(item, false)
  })
  plantSelected.value = []
}
const echo = () => {
  if (table.value?.selection?.isEcho) {
    //回显
    nextTick(() => {
      if (plantSelected.value && plantSelected.value.length) {
        table.value.listData.forEach((item: any) => {
          const result = plantSelected.value.find((row) => row[table.value.selection.rowKey] == item[table.value.selection.rowKey])
          if (result) {
            tableRef.value.toggleRowSelection(item, true)
          }
        })
      }
    })
  }
}

// 单选
const select = (selection: any, row: any) => {
  if (table.value?.selection?.isEcho) {
    const result = selection.some((item: any) => item[table.value.selection.rowKey] == row[table.value.selection.rowKey])
    if (result) {
      plantSelected.value.push(row)
    } else {
      plantSelected.value = plantSelected.value.filter((item) => item[table.value.selection.rowKey] !== row[table.value.selection.rowKey])
    }
  } else {
    plantSelected.value = selection
  }
}
// 全选
const selectAll = (selection: any) => {
  if (table.value?.selection?.isEcho) {
    if (selection.length) {
      selection.forEach((row: any) => {
        const result = plantSelected.value.some((item) => item[table.value.selection.rowKey] == row[table.value.selection.rowKey])
        if (!result) {
          plantSelected.value.push(row)
        }
      })
    } else {
      table.value.listData.forEach((row: any) => {
        plantSelected.value = plantSelected.value.filter((item) => item[table.value.selection.rowKey] !== row[table.value.selection.rowKey])
      })
    }
  } else {
    plantSelected.value = selection
  }
}

const handleInfoClick = (row: any, text: any) => {
  //编辑 详情
  emit('handleInfoClick', row, text)
}
const handleClick = (row: any) => {
  emit('handleClick', row)
}
const sizeChange = (val: any) => {
  //分页
  emit('update:pageSize', val)
  emit('paginationChange')
}
const currentChange = (val: any) => {
  //分页
  emit('update:pageNo', val)
  emit('paginationChange')
}
const getIndex = (index: any) => {
  //序号
  return index + 1 * (pageNo.value - 1) * pageSize.value + 1 + ''
}
const handleTableHeader = () => {
  CustomHeaderRef.value.open(
    //使用ref保证单向数据流问题
    true,
    deepClone(table.value.ExistingFieldsList),
    deepClone(table.value.list)
  )
}
// 序号和复选框
const isIndexOrSelection = (text: any) => {
  return table.value.type.indexOf(text) != -1
}
const isHeaderSubmit = (list: any) => {
  //保存 更新表头
  indexedDB.getData(route.path).then((res) => {
    const data = res.data
    if (!data) {
      indexedDB.addData(route.path, list)
    } else {
      indexedDB.updateData(route.path, list)
    }
  })
  table.value.ExistingFieldsList = list
}
// 删除清空选中
const deletePlantSelected = (item: any, index: number) => {
  plantSelected.value.splice(index, 1)
  tableRef.value.toggleRowSelection(item, false)
  emit('paginationChange')
}
// 全部删除
const handleClearAll = () => {
  plantSelected.value.forEach((item: any) => {
    tableRef.value.toggleRowSelection(item, false)
  })
  plantSelected.value = []
  emit('paginationChange')
}
// 展开收起
const setCollapse = () => {
  collapse.value = !collapse.value
  if (collapse.value) {
    largeScreenHeight.value = 200
  } else {
    largeScreenHeight.value = 350
  }
}
// 判断高度
const checkScreenSize = () => {
  if (!props.isLarge) {
    largeScreenHeight.value = 0
    return
  }
  const screenHeight = window.innerHeight
  if (screenHeight > 800) {
    isLargeScreen.value = true
  } else {
    isLargeScreen.value = false
  }
}

onMounted(() => {
  getHeader()
  checkScreenSize()
  window.addEventListener('resize', checkScreenSize)
})

onUnmounted(() => {
  window.removeEventListener('resize', checkScreenSize)
})
defineExpose({
  clearSelection,
})
</script>
<style scoped lang="scss">
.location {
  position: relative;
  .tableSelect {
    position: absolute;
    right: -5px;
    bottom: 10px;
    z-index: 999;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 50px;
    height: 50px;
    font-size: 12px;
    color: #fff;
    text-align: center;
    background-color: #4e88f3;
    border-radius: 50%;
  }
}
.popoverTitle {
  width: 100%;
  padding-bottom: 5px;
  margin-bottom: 5px;
  border-bottom: 1px solid #ccc;
}
.c4e88f3 {
  font-weight: 700;
  color: #4e88f3;
}
.popoverConten {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 5px;
  align-items: center;
  max-height: 300px;
  padding-bottom: 5px;
  overflow-y: scroll;
  border-bottom: 1px solid #ccc;
}
.largeContent {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-content: flex-start;
  width: 100%;
  height: calc(100% - 58px);
  overflow-y: scroll;
}
.popoverContenItem {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: auto;
  height: 30px;
  padding: 5px;
  color: #666;
  background-color: #f4f4f5;
  &:hover {
    background-color: #eaeaea;
  }
}
.footerBut {
  display: flex;
  gap: 10px;
  align-items: center;
  margin-top: 10px;
}
.largeScreen {
  width: 100%;
  padding: 5px;
  margin-top: 10px;
  border: 1px dashed #ccc;
  border-radius: 4px;
  .largeScreenTitle {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-bottom: 5px;
    margin-bottom: 5px;
    border-bottom: 1px solid #ccc;
  }
}
.myTable {
  width: 100%;
  height: calc(100vh - 335px);
  .pointer {
    cursor: pointer;
  }
}
.remark {
  display: -webkit-box;
  width: 100%;
  max-height: 60px;
  overflow: hidden;
  line-height: 1.5em; /* 行高，根据实际情况调整 */
  text-overflow: ellipsis;
  white-space: pre-line;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3; /* 控制显示的行数 */
}
.auto-height-table {
  height: calc(100vh - 160px);
}
</style>
<style lang="scss">
.el-scrollbar {
  .el-scrollbar__bar.is-horizontal {
    // 调整横向滚动条高度
    height: 14px;
  }
  .el-scrollbar__bar.is-vertical {
    // 调整纵向滚动条宽度
    width: 14px;
  }
}
</style>
